package com.ouman.luoliluoli;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ouman.luoliluoli.adapters.DaysRecyclerViewAdapter;
import com.ouman.luoliluoli.models.DaysModel;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.ouman.luoliluoli.utils.AppHelper;
import com.ouman.luoliluoli.utils.DragItemDays;
import com.ouman.luoliluoli.utils.GridSpacingItemDecoration;
import com.ouman.luoliluoli.utils.LocalSaveHelper;


public class DaysFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    private RecyclerView recyclerViewDays;
    private ArrayList<DaysModel> daysArrayList;
    private DaysRecyclerViewAdapter daysRecyclerViewAdapter;

    private SwipeRefreshLayout swipeRefreshLayout;

    private String STORAGE_FILENAME = "daysDataArray";
    private LocalSaveHelper saveHelper;
    private Integer daysDelta;
    private Integer newDaysDelta;

    private String choosenDate;
    private Boolean isClickedDate = false;

    public DaysFragment() {
        // Required empty public constructor
    }

    public static DaysFragment newInstance(String param1, String param2) {
        DaysFragment fragment = new DaysFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_days, container, false);
        ((MainActivity) getActivity()).setAppBarElevation(16);
        ((MainActivity) getActivity()).disableCollapsingLayoutTitle();
        ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("DAYS");

        recyclerViewDays = (RecyclerView) view.findViewById(R.id.recyclerview_days);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshDays);
        ((MainActivity) getActivity()).showFloatingActionButton();

        saveHelper = new LocalSaveHelper();
        print("初始化了saver。");
        daysArrayList = new ArrayList<>();

        if (AppHelper.appIsFirstRun(getActivity())){
            daysArrayList = loadPlaceHolderDaysData();
        } else {
            daysArrayList = readAndUpdateDaysData();
        }
        if (daysArrayList != null && daysArrayList.size() >= 1){
            print("===有数据！！");
            // 说明本地有数据，那就显示数据把
            // 设置卡片布局
            StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
            recyclerViewDays.setLayoutManager(manager);
            recyclerViewDays.setItemAnimator(new DefaultItemAnimator());
            recyclerViewDays.addItemDecoration(new GridSpacingItemDecoration(2,10,true));

            daysRecyclerViewAdapter = new DaysRecyclerViewAdapter(getActivity(), daysArrayList);
            recyclerViewDays.setAdapter(daysRecyclerViewAdapter);
            recyclerViewDays.addOnScrollListener(new RecyclerView.OnScrollListener() {
                int y;
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (newState == recyclerViewDays.SCROLL_STATE_IDLE && y>0){
                        ((MainActivity) getActivity()).hideFloatingActionButton();
                    }else if(newState == recyclerViewDays.SCROLL_STATE_IDLE && y<0){
                        ((MainActivity) getActivity()).showFloatingActionButton();
                    }
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    y = dy;
                    //上滑隐藏fab
                    if (dy > 0)
                    {
                        ((MainActivity) getActivity()).hideFloatingActionButton();
                    }else{
                        ((MainActivity) getActivity()).showFloatingActionButton();
                    }
                }
            });

        } else {
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_main,
                    new DaysBlankFragment()).commit();
        }


        //add swipe refresh on recycler view
        swipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_dark, android.R.color.holo_red_light,
                android.R.color.holo_blue_light, android.R.color.holo_purple);
        swipeRefreshLayout.setProgressViewEndTarget(true, 200);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                daysRecyclerViewAdapter.notifyDataSetChanged();
//                recyclerViewDays.setAdapter(daysRecyclerViewAdapter);
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getActivity(), "更新了", Toast.LENGTH_SHORT).show();
            }
        });

        // DAYS 的列表支持拖动排序，滑动删除
        ItemTouchHelper helper=new ItemTouchHelper(new DragItemDays(daysRecyclerViewAdapter));
        helper.attachToRecyclerView(recyclerViewDays);

        return view;
    }

    private ArrayList<DaysModel> loadPlaceHolderDaysData(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        int y = c.get(Calendar.YEAR);
        int m = c.get(Calendar.MONTH)+1;
        int d = c.get(Calendar.DAY_OF_MONTH);
        ArrayList<DaysModel> daysArrayListPlaceHolder = new ArrayList<>();

        String toDateString1 = y + "-" + m + "-" + (d+2) + " " + "12:59:59";
        String toDateString2 = y + "-" + (m-1) + "-" + d + " " + "12:59:59";
        Date dateNow = c.getTime();
        try{
            Date toDate1 = format.parse(toDateString1);
            Date toDate2 = format.parse(toDateString2);

            DaysModel one_day = new DaysModel();
            Integer daysDelta1 = differentDaysByMillisecond(dateNow, toDate1);
            one_day.setTitle("欢迎使用萝莉萝莉倒数日");
            one_day.setDesc("在这里记录你期待的日子");
            one_day.setDate(toDateString1);
            one_day.setDone(false);
            one_day.setDaysDelta(daysDelta1);
            // 不是保存DayModel这个类，而是保存一个列表，大哥
            daysArrayListPlaceHolder.add(one_day);

            DaysModel one_day2 = new DaysModel();
            Integer daysDelta2 = differentDaysByMillisecond(dateNow, toDate2);
            one_day2.setTitle("来完成我们的小目标");
            one_day2.setDesc("如果事情已经完成或者标记为完成将会被划去");
            one_day2.setDate(toDateString2);
            one_day2.setDone(false);
            one_day2.setDaysDelta(daysDelta2);
            // 不是保存DayModel这个类，而是保存一个列表，大哥
            daysArrayListPlaceHolder.add(one_day2);
            return daysArrayListPlaceHolder;
        } catch (ParseException e){

        }
        return daysArrayListPlaceHolder;
    }

    private ArrayList<DaysModel> readAndUpdateDaysData(){
        // get saved days data
       try{
           print("尝试读取数据");
           SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           Calendar c = Calendar.getInstance();
           Date dateNow = c.getTime();

           daysArrayList = readFromInternalStorage();
           print("更新数据中");
           for (int i=0;i< daysArrayList.size();i++){
               try{
                   Date dateSaved = format.parse(daysArrayList.get(i).getDate());
                   newDaysDelta = differentDaysByMillisecond(dateNow, dateSaved);
                   if (newDaysDelta < 0){
                       daysArrayList.get(i).setDone(true);
                   }
                   print("updated delta: " + newDaysDelta);
                   daysArrayList.get(i).setDaysDelta(newDaysDelta);
               } catch (ParseException e){

               }
           }
           return daysArrayList;
       } catch (IOException e){

       }
       return daysArrayList;

    }
    // read array list from internal storage
    @SuppressWarnings("unchecked")
    private ArrayList<DaysModel> readFromInternalStorage() throws IOException {
        ArrayList<DaysModel> toReturn = null;
        try {
            FileInputStream fis = getActivity().openFileInput(STORAGE_FILENAME);
            ObjectInputStream oi = new ObjectInputStream(fis);
            toReturn = (ArrayList<DaysModel>) oi.readObject();
            oi.close();
        } catch (ClassNotFoundException e) {
            Log.e("InternalStorage", e.getMessage());
        }
        return toReturn;
    }


    public class SpaceItemDecoration extends RecyclerView.ItemDecoration{
        private int space;
        public SpaceItemDecoration(int space) {
            this.space = space;
        }
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if(parent.getChildPosition(view) != 0)
                outRect.top = space;
        }
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);

        Calendar cal = Calendar.getInstance();
        final Integer year = cal.get(Calendar.YEAR);
        final Integer month = cal.get(Calendar.MONTH);
        final Integer day = cal.get(Calendar.DAY_OF_MONTH);

        FloatingActionButton mainFab = ((MainActivity) getActivity()).getFloatingActionButton();
        mainFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View popDialogView = LayoutInflater.from(getContext()).inflate(R.layout.days_add_popup_dialog, null);
                final EditText editTextTitle = (EditText) popDialogView.findViewById(R.id.editTextTitle);
                final EditText editTextDesc = (EditText) popDialogView.findViewById(R.id.editTextDesc);

                final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setView(popDialogView);
                builder.setTitle("添加新日子");
                builder.setPositiveButton("添加", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // 把添加时间保存到internal storage中， 我们在saveToInternalStorage
                        // 中已经设置了保存方式为APPEND，因此不会覆盖而是追加
                        if (!isClickedDate){
                            Toast.makeText(getActivity(), "未选择日期", Toast.LENGTH_SHORT).show();
                        } else {
                            String title = editTextTitle.getText().toString();
                            String desc = editTextDesc.getText().toString();
                            DaysModel new_day = new DaysModel();
                            new_day.setTitle(title);
                            new_day.setDesc(desc);
                            new_day.setDate(choosenDate);
                            new_day.setDone(false);
                            new_day.setDaysDelta(daysDelta);
                            // 不是保存DayModel这个类，而是保存一个列表，大哥
                            daysArrayList.add(0, new_day);
                            System.out.println(daysArrayList.size());
                            saveHelper.saveToInternalStorage(daysArrayList, STORAGE_FILENAME, getActivity(), Context.MODE_PRIVATE);
                            // 保存之后通知recycle view刷新数据
                            daysRecyclerViewAdapter.notifyDataSetChanged();
                            Toast.makeText(getContext(), "添加成功", Toast.LENGTH_SHORT).show();
                            isClickedDate = false;
                        }
                    }
                });
                builder.show();

                final TextView date = (TextView) popDialogView.findViewById(R.id.date);
                date.setText("今天是: " + year + "-" + (month+1) + "-" + day);
                Button dateChoose = (Button) popDialogView.findViewById(R.id.buttonDateChoose);
                dateChoose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new DatePickerDialog(getActivity(),
                                new DatePickerDialog.OnDateSetListener() {
                                    @Override
                                    public void onDateSet(DatePicker view, int year, int month, int day) {
                                        // TODO Auto-generated method stub
                                        int mYear = year;
                                        int mMonth = month;
                                        int mDay = day;
                                        // 更新EditText控件日期 小于10加0
                                        date.setText(new StringBuilder()
                                                .append("执行日期: ")
                                                .append(mYear)
                                                .append("-")
                                                .append((mMonth + 1) < 10 ? "0"
                                                        + (mMonth + 1) : (mMonth + 1))
                                                .append("-")
                                                .append((mDay < 10) ? "0" + mDay : mDay));
                                        String dateString = mYear + "-" + (mMonth+1) + "-" + mDay + " " + "12:59:59";
                                        System.out.println(dateString);
                                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        Calendar c = Calendar.getInstance();
                                        Date dateNow = c.getTime();
                                        try{
                                            Date date1 = format.parse(dateString);
                                            daysDelta = differentDaysByMillisecond(dateNow, date1);
                                            if(daysDelta < 0){
                                                Toast.makeText(getActivity(), "所选日期已经过去了哟, 此为无效日期", Toast.LENGTH_SHORT).show();
                                            } else {
                                                choosenDate = mYear + "-" + (mMonth+1) + "-" + mDay + " " + "12:59:59";
                                                System.out.println("date!! delta: " + daysDelta);
                                                isClickedDate = true;
                                            }
                                        } catch (ParseException e){

                                        }

                                    }
                                }, year, month, day).show();
                    }
                });

            }
        });
    }

    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    public void print(String s){
        System.out.println(s);
    }
}
